package com.itheima.reggie.exception;

import com.itheima.reggie.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 定义项目异常处理器
 */
@RestControllerAdvice
@Slf4j
public class ProjectExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public Result<String> businessExceptionHandle(BusinessException exception){
        log.info("异常处理器拦截到业务级异常==>"+exception.getMessage());
        return Result.error(exception.getMessage());
    }

    @ExceptionHandler(SystemException.class)
    public Result<String> systemExceptionHandle(SystemException exception){
        log.info("异常处理器拦截到系统级异常==>"+exception.getMessage());
        return Result.error(exception.getMessage());
    }

    /**
     * sql完整性约束违反异常处理器
     * @param exception sql完整性约束违反异常
     * @return 通用返回结果
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> sQLIntegrityConstraintViolationExceptionHandler(SQLIntegrityConstraintViolationException exception){
        log.info("异常处理器拦截到异常==>"+exception.getMessage());
        if(exception.getMessage().contains("Duplicate entry")){
            String[] strings = exception.getMessage().split(" ");
            String msg = strings[2].replaceAll("'","")+"已经存在,添加失败!";
            return Result.error(msg);
        }
        return Result.error("发生未知错误");
    }

    @ExceptionHandler(Exception.class)
    public Result<String> exceptionHandler(Exception exception){
        log.info("异常处理器拦截到其他异常==>"+exception.getMessage());
        exception.printStackTrace();
        return Result.error("其他异常");
    }


}
